package com.jy.modules.cims.deal.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService;
import com.jy.modules.cims.component.common.service.TCMmRaisePlanService;
import com.jy.modules.cims.component.common.service.TCMmRefundPlanService;
import com.jy.modules.cims.component.loan.CLoanImpl;
import com.jy.modules.cims.component.loan.TBJCLoanImpl;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.component.tbj.ITBJBusinessClient;
import com.jy.modules.cims.component.tbj.TBJSendService;
import com.jy.modules.cims.data.common.dao.TCMmCreditDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmLoanDetailDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmRefundPlanDTO;
import com.jy.modules.cims.data.dao.AuditResultDao;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dao.DictDetailDao;
import com.jy.modules.cims.data.dao.LoanDao;
import com.jy.modules.cims.data.dao.LoanResultDao;
import com.jy.modules.cims.data.dto.ConfirmParamDto;
import com.jy.modules.cims.data.dto.ConfirmParamDto.LoanApproveInfo;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.Df02FileDto;
import com.jy.modules.cims.data.dto.DictDetailDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockParamDto;
import com.jy.modules.cims.data.dto.RefundPlanDTO;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateResultDto;
import com.jy.modules.cims.data.dto.inter.tbj.TBJMessage;
import com.jy.modules.cims.data.dto.inter.tbj.TBJResponse;
import com.jy.modules.cims.data.dto.inter.tbj.fk.LoanResultDto;
import com.jy.modules.cims.data.dto.inter.tbj.jj.AbortDTO;
import com.jy.modules.cims.data.dto.inter.tbj.sh.AuditResultDto;
import com.jy.modules.cims.data.dto.loan.LoanFundOutDto;
import com.jy.modules.cims.data.dto.loan.LoanFundOutDto.LoanFundOutInfo;
import com.jy.modules.cims.data.dto.loan.LoanFundOutResultDto;
import com.jy.modules.cims.data.dto.loan.LoanOfferResultDto;
import com.jy.modules.cims.data.dto.loan.LoanRedemptionDto;
import com.jy.modules.cims.data.dto.loan.LoanResultDetail;
import com.jy.modules.cims.data.dto.masterdata.ResRepaymentPlanBean;
import com.jy.modules.cims.data.interact.core.loan.request.RequsetMasterdataDTO;
import com.jy.modules.cims.interact.CIRLoanIFImpl;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.interact.InteractClassInvokeService;
import com.jy.modules.cims.settle.service.CreditRedemptionService;
import com.jy.modules.platform.sysdict.impl.SysDictAPImpl;
import com.jy.platform.api.org.SessionAPI;
import com.jy.platform.api.org.UserInfo;
import com.jy.platform.api.sysdict.SysDictDetailVo;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.QueryReqBean;
import com.tongbanjie.open.api.enums.EntryResponseEnum;

/**
 * 交易处理服务层
 */
@Service("com.jy.modules.cims.deal.service.LoanDealService")
public class LoanDealService {

	private static Logger logger = LoggerFactory.getLogger(ExportAndImport.class);

	@Autowired
	public LoanDao loanDao;

	@Autowired
	public DealDao dealDao;
	
	@Autowired
	private DictDetailDao dictDetailDao;

	@Autowired
	public AuditResultDao auditResultDao;

	@Autowired
	public LoanResultDao loanResultDao;

	@Autowired
	public TCMmLoanDetailDao tCMmLoanDetailDao;

	@Autowired
	public TCMmCreditDetailDao tCMmCreditDetailDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	private TCMmCooperorgDealService cooperorgDealService;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	private ICInteract iCInteract;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	private IInteractAssist iInteractAssist;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmRefundPlanService")
	private TCMmRefundPlanService refundPlanService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.tbj.TBJSendService")
	private TBJSendService tbjSendService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.InteractClassInvokeService")
	private InteractClassInvokeService interactClassInvokeService;

	@Autowired
	private SysDictAPImpl sysDictAPI;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.CLoanImpl")
	public CLoanImpl loanImpl;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CIRLoanIFImpl")
	private CIRLoanIFImpl cIRLoanIFImpl;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.tbj.TBJBusinessClient")
	private ITBJBusinessClient iTBJBusinessClient;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.TBJCLoanImpl")
	private TBJCLoanImpl tbjCLoanImpl;

	@Autowired
	@Qualifier("com.jy.modules.cims.settle.service.CreditRedemptionService")
	public CreditRedemptionService creditRedemptionService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
	public TCMmCreditDealDetailService creditDealDetailService;

	@Autowired
	private SessionAPI sessionAPI;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmRaisePlanService")
	private TCMmRaisePlanService tCMmRaisePlanService;

	/**
	 * 
	 * @Title getDealDetailByLoanList
	 * @Description TODO
	 * @return List<LoanDetailDto>
	 * @author lizhiqiang
	 * @date 2015-2-11-下午2:46:01
	 * @update
	 * @throws
	 */
	public List<LoanDetailDto> getDealDetailByLoanList(Map<String, Object> searchParams) {
		return loanDao.getDealDetailByLoanListByPaging(searchParams);
	}

	/**
	 * 
	 * @Title getDealDetailByLoanList
	 * @Description TODO
	 * @return List<LoanDetailDto>
	 * @author lizhiqiang
	 * @date 2015-2-11-下午2:46:01
	 * @update
	 * @throws
	 */
	public List<LoanDetailDto> getDealDetailByLoanListForExport(Map<String, Object> searchParams) {
		List<LoanDetailDto> list = loanDao.getDealDetailByLoanList(searchParams);
		List<LoanDetailDto> loanDetaillist = new ArrayList<LoanDetailDto>();
		for (LoanDetailDto loanDetailDto : list) {
			loanDetailDto.setSex(getDictDetailName("SEX", loanDetailDto.getSex()));// 性别
			loanDetailDto.setCardType(getDictDetailName("IDTYPE", loanDetailDto.getCardType()));// 证件类型
			loanDetailDto.setDiploma(getDictDetailName("EDUCATION", loanDetailDto.getDiploma()));// 学历
			loanDetailDto.setIsHasHouse(getDictDetailName("HOUSETYPE", loanDetailDto.getIsHasHouse()));
			loanDetailDto.setMarryStatus(getDictDetailName("MARITALSTATUS", loanDetailDto.getMarryStatus()));
			loanDetailDto.setIsHasChild(getDictDetailName("CHILDSTATUS", loanDetailDto.getIsHasChild()));
			if(CimsConstant.COOPERORG_CODE_TBJ.equals(loanDetailDto.getCooperorgCode())){
				loanDetailDto.setCompanyType(tbjGetDictDetailName("cims_jType", loanDetailDto.getCompanyType()));
				loanDetailDto.setLoanPurpose(tbjGetDictDetailName("cims_loanPurpose", loanDetailDto.getLoanPurpose()));
				loanDetailDto.setHomeType(tbjGetDictDetailName("cims_homeType", loanDetailDto.getHomeType()));
				loanDetailDto.setDuty(tbjGetDictDetailName("cims_jPosition", loanDetailDto.getDuty()));
				
			}else{
				loanDetailDto.setCompanyType(getDictDetailName("JOBNATURE", loanDetailDto.getCompanyType()));
				loanDetailDto.setLoanPurpose(getDictDetailName("LOANPURPOSE", loanDetailDto.getLoanPurpose()));
				loanDetailDto.setHomeType(getDictDetailName("HOUSETYPE", loanDetailDto.getHomeType()));
				loanDetailDto.setDuty(getDictDetailName("DUTY", loanDetailDto.getDuty()));
			}
			loanDetailDto.setRepayType(getDictDetailName("CM_REPAYMENTWAY", loanDetailDto.getRepayType()));
			loanDetailDto.setHouseholdType(getDictDetailName("CENSUSTYPE", loanDetailDto.getHouseholdType()));
			loanDetailDto.setLoanStatus(getDictDetailName("C_CL_LOAN_STATUS", loanDetailDto.getLoanStatus()));
			loanDetailDto.setCooperorgName(getDictDetailName("cooperorgCodes", loanDetailDto.getCooperorgCode()));
			loanDetaillist.add(loanDetailDto);
		}
		return loanDetaillist;
	}

	/**
	 * 查询合同号
	 * 
	 * @param searchParams
	 * @return
	 */
	private Map<String, List<String>> getDealDetailByLoanListContractNo(String startRownum, String endRownum, String cooperorgType) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("startRownum", startRownum);
		paramMap.put("endRownum", endRownum);
		paramMap.put("cooperorgType", cooperorgType);
		List<LoanDetailDto> list = loanDao.getLoanContractNoList(paramMap);
		Map<String, List<String>> contractDealCodeMap = new HashMap<String, List<String>>();
		List<String> contractNo = new ArrayList<String>();
		List<String> dealCode = new ArrayList<String>();
		for (LoanDetailDto loanDetailDto : list) {

			contractNo.add(loanDetailDto.getContractNo());
			dealCode.add(loanDetailDto.getDealCode());
		}
		contractDealCodeMap.put("contractNo", contractNo);
		contractDealCodeMap.put("dealCode", dealCode);
		return contractDealCodeMap;
	}

	/**
	 * 更新贷款状态和新增债权信息
	 * 
	 * @param searchParams
	 * @return
	 */
	public void getDealDetailByLoanListType() {

		String cooperorgType = "03";

		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("cooperorgType", cooperorgType);
			List<LoanDetailDto> contractNoList = loanDao.getLoanContractNoAll(searchParams);
			int contractNoListLength = contractNoList.size();

			if (contractNoListLength > 0) {
				int count = 0;
				int leftNumber = contractNoListLength % CimsConstant.LOAN_DEAL_RESULT;
				int rightNumber = contractNoListLength / CimsConstant.LOAN_DEAL_RESULT;
				int countNo = (leftNumber == 0 ? rightNumber : rightNumber + 1);
				for (int i = 0; i < countNo; i++) {

					int countEnd = contractNoListLength - count;
					String startRownum = String.valueOf(count + 1);
					String endRownum = "";
					if (countEnd > CimsConstant.LOAN_DEAL_RESULT) {
						endRownum = String.valueOf(count + CimsConstant.LOAN_DEAL_RESULT);
						count += CimsConstant.LOAN_DEAL_RESULT;
					} else {

						endRownum = String.valueOf(count + countEnd);
						count += countEnd;
					}

					Map<String, List<String>> contractDealCodeMap = this.getDealDetailByLoanListContractNo(startRownum, endRownum, cooperorgType);
					List<String> contractNos = contractDealCodeMap.get("contractNo");

					LoanOfferResultDto loanOfferResultDto = new LoanOfferResultDto();

					List<LoanResultDetail> loanResultDetails = new ArrayList<LoanResultDetail>();
					for (int s = 0; s < contractNos.size(); s++) {
						String contractNo = contractNos.get(s);
						LoanResultDetail loanResultDetail = new LoanResultDetail();
						loanResultDetail.setContractNo(contractNo);
						loanResultDetails.add(loanResultDetail);
					}
					loanOfferResultDto.setLoanResultDetail(loanResultDetails);
					String busiNoForInteract = iInteractAssist.getInteractNo();
					loanOfferResultDto.setDealCode(busiNoForInteract);
					List<LoanResultDetail> returnInformation = cIRLoanIFImpl.queryLoanOfferResultRepayment(loanOfferResultDto);

					if (returnInformation.size() > 0) {
						updateLoanDetailStatus(returnInformation);
						logger.info("接口流水号：" + busiNoForInteract + "更新放款结果成功");
					}
					logger.info("接口流水号：" + busiNoForInteract + "接口返回结果为空");
				}
			}
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.UPDATE_LOAN_RESULT_FIELD + e.getMessage());
		}
	}

	/**
	 * 获取主数据还款计划信息
	 * 
	 * @param searchParams
	 * @return
	 */
	public ResRepaymentPlanBean getSettleByMasterdataListType(RequsetMasterdataDTO requsetMasterdataDTO) {

		try {
			ResRepaymentPlanBean resRepaymentPlanBean = cIRLoanIFImpl.queryMasterdataResultRepayment(requsetMasterdataDTO);
			return resRepaymentPlanBean;
		} catch (Exception e) {
			e.printStackTrace();
			throw new SysAssistException(CimsExceptionConstant.GET__MASTERDATA_FIELD + e.getMessage());
		}
	}

	/**
	 * 
	 * @Title updateTCMmQuotaLoanDetailLoanStatus 贷款回盘文件状态修改
	 * @param List
	 *            <Object>
	 * @author zhuwenbin
	 * @date 2015-03-02-下午19:46:01
	 * @return LoanFundOutDto
	 * @throws Exception
	 */
	public LoanFundOutDto updateTCMmLoanDetailLoanStatus(List<Object> objList, TCMmCooperorgDealDTO cooperorgDealDTO) throws Exception {

		int line = objList.size();
		Df02FileDto dfdto = null;

		StringBuffer failIds = new StringBuffer();
		StringBuffer successIds = new StringBuffer();
		// 获取待修改贷款信息id
		LoanFundOutDto loanFundOutDto = new LoanFundOutDto();
		List<LoanFundOutInfo> loanFundOutInfoList = new ArrayList<LoanFundOutInfo>();
		// 第一条为汇总信息从1开始遍历
		for (int i = 1; i < line; i++) {

			dfdto = (Df02FileDto) objList.get(i);
			LoanFundOutInfo outinfo = loanFundOutDto.new LoanFundOutInfo();
			// 判断放款是否成功
			if ("0000".equals(dfdto.getResultCode())) {
				// 放款成功
				successIds.append(dfdto.getSerNo());
				successIds.append(",");
				outinfo.setOperType(CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_SUCCESS);
			} else {
				// 放款失败
				failIds.append(dfdto.getSerNo());
				failIds.append(",");
				outinfo.setOperType(CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_FAIL);
			}

			outinfo.setContractNo(dfdto.getUserdefinedNo());
			outinfo.setOperReason(dfdto.getResultNote());
			loanFundOutInfoList.add(outinfo);

		}

		// 批量修改放款成功贷款交易
		if (successIds.length() > 0) {
			successIds = successIds.replace(successIds.lastIndexOf(","), successIds.length(), "");
			this.updateTCMmLoanDetailLoanStatusByIds(successIds.toString(), CimsConstant.LOAN_EACH_STATUS_CORE, CimsConstant.LOAN_FUNDOUT_WIN);

		}
		// 批量修改放款失败贷款交易
		if (failIds.length() > 0) {
			failIds.replace(failIds.lastIndexOf(","), failIds.length(), "");
			this.updateTCMmLoanDetailLoanStatusByIds(failIds.toString(), CimsConstant.LOAN_EACH_STATUS_CORE, CimsConstant.LOAN_FUNDOUT_LOSE);
		}

		String busiNoForInteract = iInteractAssist.getInteractNo();
		// 交易流水
		loanFundOutDto.setDealCode(busiNoForInteract);
		// 设置放款结果列表
		loanFundOutDto.setLoanFundOutInfoList(loanFundOutInfoList);

		iInteractAssist.registerDealIrtService(busiNoForInteract);
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "loanFundOutconfirm", loanFundOutDto);
		// 调用放款确认接口
		LoanFundOutResultDto dto = loanFundOutconfirm(loanFundOutDto);
		if (dto.success) {
			String[] keys = successIds.toString().split(",");
			for (String key : keys) {
				// 放款成功写债权表
				this.insertCredit(key, cooperorgDealDTO);
			}
		}

		return loanFundOutDto;
	}

	/**
	 * 
	 * @Title updateLoanDetailStatus 通过合同号 贷款回盘文件状态修改
	 * @throws Exception
	 */
	public boolean updateLoanDetailStatus(List<LoanResultDetail> loanResultDetail) throws Exception {

		int line = loanResultDetail.size();

		StringBuffer successContractNos = new StringBuffer();
		for (int i = 0; i < line; i++) {

			LoanResultDetail outinfo = loanResultDetail.get(i);
			// 判断放款是否成功
			if (CimsConstant.CORE_LOAN_RESULT_TYPE_SUCCESS.equals(outinfo.getOperType())) {
				// 放款成功
				successContractNos.append(outinfo.getContractNo());
				successContractNos.append(",");
				this.updateTCMmLoanDetailLoanStatusByContractNo(outinfo.getContractNo(), CimsConstant.LOAN_EACH_STATUS_CORE,
						CimsConstant.LOAN_FUNDOUT_WIN);

			} else if (CimsConstant.CORE_LOAN_RESULT_TYPE_RJT.equals(outinfo.getOperType())) {
				// 合同废弃
				this.updateTCMmLoanDetailLoanStatusByContractNo(outinfo.getContractNo(), CimsConstant.LOAN_EACH_STATUS_CORE,
						CimsConstant.LOAN_FUNDOUT_RJT);
			}
		}

		String[] keys = successContractNos.toString().split(",");
		
		if (!successContractNos.toString().equals("")) {

			// 更新债权信息
			for (int n = 0; n < keys.length; n++) {
				String contractNo = keys[n];
				// 放款成功写债权表
				tbjCLoanImpl.insertCreditByContractNo(contractNo, null);
				
			}
		}

		return true;
	}

	/**
	 * @Description 根据贷款明细id拒绝放款
	 * @author shengzhoutao
	 * @param loanDetailIds
	 *            多个贷款明细id
	 * @return
	 * @throws Exception
	 */
	public String doRefusedLendByLoanDetailIds(String loanDetailIds) throws Exception {
		if (!SimpleStringUtils.hasText(loanDetailIds)) {
			return "请选择待拒绝放款的数据！";
		}

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", loanDetailIds);
		List<LoanDetailDto> loanDetailList = loanDao.getLoanDetailByLoanDetailIds(paramMap);
		if (CollectionsUtils.isEmpty(loanDetailList)) {
			return "查询无贷款明细数据！";
		}

		LoanFundOutInfo loanFundOutInfo = null;
		LoanFundOutDto loanFundOutDto = new LoanFundOutDto();
		List<LoanFundOutInfo> loanFundOutInfoList = new ArrayList<LoanFundOutInfo>();

		for (LoanDetailDto loanDetail : loanDetailList) {
			loanFundOutInfo = loanFundOutDto.new LoanFundOutInfo();
			loanFundOutInfo.setOperType(CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_FAIL);
			loanFundOutInfo.setContractNo(loanDetail.getContractNo());
			loanFundOutInfo.setOperReason(" ");

			loanFundOutInfoList.add(loanFundOutInfo);
		}

		String busiNoForInteract = iInteractAssist.getInteractNo();// 交易流水
		loanFundOutDto.setDealCode(busiNoForInteract);
		loanFundOutDto.setLoanFundOutInfoList(loanFundOutInfoList);// 设置放款结果列表

		iInteractAssist.registerDealIrtService(busiNoForInteract);
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "loanFundOutconfirm", loanFundOutDto);

		// 调用放款确认接口
		LoanFundOutResultDto dto = loanFundOutconfirm(loanFundOutDto);
		if (dto.success) {
			paramMap = new HashMap<String, Object>();
			paramMap.put("ids", loanDetailIds);
			paramMap.put("loanStatus", CimsConstant.LOAN_FUNDOUT_LOSE_M);
			loanDao.updateLoanStatusByIds(paramMap);

			return "拒绝放款成功！";
		}

		return "拒绝放款失败！";
	}

	/**
	 * @Description 根据多个交易流水拒绝放款
	 * @author shengzhoutao
	 * @param dealIds
	 *            多个交易流水id
	 * @return
	 * @throws Exception
	 */
	public String doRefusedLendByDealIds(String dealIds) throws Exception {
		if (!SimpleStringUtils.hasText(dealIds)) {
			return "请选择待拒绝放款的数据！";
		}

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dealIds", dealIds);
		List<LoanDetailDto> loanDetailList = loanDao.getLoanDetailByDealIds(paramMap);
		if (CollectionsUtils.isEmpty(loanDetailList)) {
			return "查询无贷款明细数据！";
		}

		LoanFundOutInfo loanFundOutInfo = null;
		LoanFundOutDto loanFundOutDto = new LoanFundOutDto();
		List<LoanFundOutInfo> loanFundOutInfoList = new ArrayList<LoanFundOutInfo>();

		for (LoanDetailDto loanDetail : loanDetailList) {
			loanFundOutInfo = loanFundOutDto.new LoanFundOutInfo();
			loanFundOutInfo.setOperType(CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_FAIL);
			loanFundOutInfo.setContractNo(loanDetail.getContractNo());
			loanFundOutInfo.setOperReason(" ");

			loanFundOutInfoList.add(loanFundOutInfo);
		}

		String busiNoForInteract = iInteractAssist.getInteractNo();// 交易流水
		loanFundOutDto.setDealCode(busiNoForInteract);
		loanFundOutDto.setLoanFundOutInfoList(loanFundOutInfoList);// 设置放款结果列表

		iInteractAssist.registerDealIrtService(busiNoForInteract);
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "loanFundOutconfirm", loanFundOutDto);

		// 调用放款确认接口
		LoanFundOutResultDto dto = loanFundOutconfirm(loanFundOutDto);
		if (dto.success) {
			paramMap.clear();
			paramMap.put("dealIds", dealIds);
			paramMap.put("loanStatus", CimsConstant.LOAN_FUNDOUT_LOSE_M);
			loanDao.updateLoanStatusByDealIds(paramMap);

			paramMap.clear();
			paramMap.put("ids", dealIds);
			paramMap.put("dealStatus", CimsConstant.DEAL_STATUS_FUNDOUT_LOSE_M);
			dealDao.updateDealStatusByIds(paramMap);

			return "拒绝放款成功！";
		}

		return "拒绝放款失败！";
	}

	/**
	 * 放款确认后插入债权信息
	 * 
	 * @param id
	 */
	public void insertCredit(String id, TCMmCooperorgDealDTO cooperorgDealDTO) {
		TCMmLoanDetailDTO loanddto = tCMmLoanDetailDao.findTCMmLoanDetailByPrimaryKey(id);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
		dto.setCreditCode(loanddto.getContractNo());
		dto.setCreditSource(CimsConstant.CREDIT_SOURCE_LOA);
		dto.setCooperorgCode(loanddto.getCooperorgCode());
		dto.setPackageNum(loanddto.getCreditPackageName());
		dto.setAgreementCode(cooperorgDealDTO.getAgreementCode());
		dto.setContractCode(cooperorgDealDTO.getContractCode());
		dto.setProductType(cooperorgDealDTO.getCooperativeAgencyProType());
		dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);
		dto.setRepayType(cooperorgDealDTO.getRepayType());//插入债权信息没有插入还款方式 zhoup 2016-0701
		paramMap.put("dto", dto);
		tCMmCreditDetailDao.insertTCMmCreditDetail(paramMap);
	}




	/**
	 * 调用放款确认接口
	 * 
	 * @param loanFundOutDto
	 */
	public LoanFundOutResultDto loanFundOutconfirm(LoanFundOutDto loanFundOutDto) {
		return iCInteract.loanFundOut(loanFundOutDto);
	}

	/**
	 * 根据ids批量修改放款状态
	 * 
	 * @param ids
	 * @param loanStatus
	 * @throws Exception
	 */
	public void updateTCMmLoanDetailLoanStatusByIds(String ids, String loanStatus, String loanDetailStatus) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		paramMap.put("loanStatus", loanStatus);
		paramMap.put("loanDetailStatus", loanDetailStatus);
		loanDao.updateTCMmLoanDetailLoanStatusByIds(paramMap);
	}

	/**
	 * 根据合同号批量修改放款状态
	 * 
	 * @param ids
	 * @param loanStatus
	 * @throws Exception
	 */
	public void updateTCMmLoanDetailLoanStatusByContractNo(String contractNo, String loanStatus, String loanDetailStatus) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("contractNos", contractNo);
		paramMap.put("loanStatus", loanStatus);
		paramMap.put("loanDetailStatus", loanDetailStatus);
		loanDao.updateTCMmLoanDetailLoanStatusByContractNos(paramMap);
	}

	/**
	 * 根据ids批量修改贷款状态
	 * 
	 * @param ids
	 * @param loanStatus
	 * @throws Exception
	 */
	public void updateLoanStatusByIds(String ids, String loanStatus) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		paramMap.put("loanStatus", loanStatus);
		loanDao.updateLoanStatusByIds(paramMap);
		// 调用释放贷款接口
		unlockLoanDetailResult(ids);
	}
	
	/**
	 * 修改贷款信息
	 * 
	 * @param ids
	 * @param loanStatus
	 * @throws Exception
	 */
	public void updateTCMmLoanDetail(Map<String, Object> paramMap) throws Exception {
	
		loanDao.updateTCMmLoanDetail(paramMap);
	}
	
	

	/**
	 * 修改高风险贷款状态
	 * 
	 * @param ids
	 * @param loanStatus
	 * @throws Exception
	 */
	public void updateRiskLoanStatusByIds(String ids, String loanStatus, String riskTime) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		paramMap.put("loanStatus", loanStatus);
		paramMap.put("riskTime", riskTime);
		loanDao.updateRiskLoanStatusByIds(paramMap);
		// 调用释放贷款接口
		unlockLoanDetailResult(ids);
	}

	/**
	 * 流标接口
	 * 
	 * @Description
	 * @param ids
	 * @param contractNo
	 * @throws Exception
	 *             void
	 * @throws
	 * @author zhangmi
	 * @date 2016-5-13
	 */
	public void updateAbortLoanStatusByIds(String ids, String contractNo) throws Exception {
		Date date = new Date();
		// 调用铜板街接口
		AbortDTO abortDto = new AbortDTO();
		abortDto.setExitTime(DateTimeUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
		abortDto.setLoanNumber(contractNo);
		TBJResponse tbjResponse = iTBJBusinessClient.abort(abortDto);
		//请求成功
		if(EntryResponseEnum.SUCESS21001.getCode().equals(tbjResponse.getRetCode())){
			String res = ((TBJMessage) tbjResponse.getData()).getResult();
			if (!"2".equals(res)) {
				// 修改本地状态
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("ids", ids);
				paramMap.put("loanStatus", CimsConstant.LOAN_FUNDOUT_LB);
				paramMap.put("riskTime", DateTimeUtils.formatDate(date, "yyyy-MM-dd"));
				loanDao.updateRiskLoanStatusByIds(paramMap);
				// 调用释放贷款接口
				unlockLoanDetailResult(ids);
				logger.info("铜板街流标接口调用成功！合同号：" + contractNo);
			} else {
				logger.info("铜板街流标接口调用失败！合同号：" + contractNo);
				throw new Exception("铜板街流标接口异常，错误编码：" + ((TBJMessage) tbjResponse.getData()).getResult() + ",错误信息：" + ((TBJMessage) tbjResponse.getData()).getMessage());
			}
		}else{
			logger.info("铜板街流标接口调用失败！合同号：" + contractNo);
			throw new Exception("铜板街流标接口调用失败！"+tbjResponse.getMessage());
		}
		

	}

	/**
	 * 
	 * @Description    紧急扣回
	 * void  
	 * @throws
	 * @author zhangmi
	 * @date 2016-6-29
	 */
	public void updateEmergencyDroppage(String contractNo) throws Exception {
		
		logger.info("紧急扣回开始>>");
		/**
		 * 状态验证
		 */
		TCMmLoanDetailDTO loanddto = tCMmLoanDetailDao.findTCMmLoanDetailByPrimaryContractNo(contractNo);
		if(null==loanddto){
			throw new Exception("贷款明细没有该合同数据："+contractNo);
		}
		String status = loanddto.getLoanStatus();
		String cooperorgCode = loanddto.getCooperorgCode();
		String loanEachStatus = loanddto.getLoanEachStatus();
		if(!(CimsConstant.LOAN_CONFIRM_WIN.equals(status)||CimsConstant.LOAN_WAY.equals(status))){
			throw new Exception("只有‘在途’，‘审批通过’才能紧急扣回！");
		}
		//铜板街机构特殊处理
		if("TBJ".equals(cooperorgCode)){
			if(CimsConstant.LOAN_WAY.equals((status))){
				//铜板街发送附件列表完毕-----正在推送进件信息
				if(CimsConstant.LOAN_EACH_STATUS_ATTACH.equals(loanEachStatus)){
					throw new Exception("商户正在接收该合同相关信息（请稍后在做紧急扣回）！");
				}else  if(CimsConstant.LOAN_EACH_STATUS_CRE.equals(loanEachStatus)
					|| CimsConstant.LOAN_EACH_STATUS_URL.equals(loanEachStatus)
					|| CimsConstant.LOAN_EACH_STATUS_SEND.equals(loanEachStatus)){
					/**
					 * 进件还未推送：直接拒绝
					 */
					//①修改数据状态，流标时间，修改状态为流标
					updateEmergencyDroppageByIds(String.valueOf(loanddto.getId()),CimsConstant.LOAN_FUNDOUT_LB);
					//②调用核心接口--发送核心接口-审批拒绝
					tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL);
				}
			}else if(CimsConstant.LOAN_CONFIRM_WIN.equals(status)){
				//调用铜板街紧急扣回接口
				tbjSendService.sendAbortByLoanNumber(contractNo);
				//①修改数据状态，流标时间，修改状态为流标
				updateEmergencyDroppageByIds(String.valueOf(loanddto.getId()),CimsConstant.LOAN_FUNDOUT_LB);
				//②调用核心接口--发送核心接口-审批拒绝
				tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL);
			}
		}else if("XS".equals(cooperorgCode)||"XQ".equals(cooperorgCode)){
			tbjSendService.sendJieYueAbortLoan(cooperorgCode, contractNo);
			//①修改数据状态，流标时间，修改状态为流标
			updateEmergencyDroppageByIds(String.valueOf(loanddto.getId()),CimsConstant.LOAN_FUNDOUT_LB);
			//②调用核心接口--发送核心接口-审批拒绝
			tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL);
		}else {
			updateEmergencyDroppageByIds(String.valueOf(loanddto.getId()),CimsConstant.LOAN_FUNDOUT_LB);
			//②调用核心接口--发送核心接口-审批拒绝
			tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL);
		}
		logger.info("紧急扣回结束>>");
	}
	/**
	 * 
	 * @Description 紧急扣回修改数据状态
	 * @param ids
	 * @throws Exception   
	 * void  
	 * @throws
	 * @author zhangmi
	 * @date 2016-6-29
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 5)
	public void updateEmergencyDroppageByIds(String ids,String status) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		paramMap.put("loanStatus", status);
		paramMap.put("riskTime", DateTimeUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		loanDao.updateRiskLoanStatusByIds(paramMap);
	}
	
	public List<String> getLoanDealCodeByContractNo(Map<String, Object> paramMap) throws Exception {
		return loanDao.getLoanDealCodeByContractNo(paramMap);
	}

	public String getDictDetailName(String dict_code, String detail_value) {
		String dictDetailName = "";
		if (!SimpleStringUtils.isBlank(dict_code) && !SimpleStringUtils.isBlank(detail_value)) {
			SysDictDetailVo sysDictDetailVo = sysDictAPI.queryDetailByDictCodeAndDeatailValue(dict_code, detail_value);
			if (sysDictDetailVo != null)
				dictDetailName = sysDictDetailVo.getDictDetailName();
		}
		return dictDetailName;
	}
	public String tbjGetDictDetailName(String dict_code, String detail_value){
		String dictDetailName = "";
		if (!SimpleStringUtils.isBlank(dict_code) && !SimpleStringUtils.isBlank(detail_value)) {
			DictDetailDto dto = new DictDetailDto();
			dto.setDictCode(dict_code);
			dto.setDictDetailValue(detail_value);
			List<DictDetailDto> list = dictDetailDao.getDictDetailDtoByCode(SearchParamUtil.getSearchParam(dto));
			if(CollectionsUtils.isNotEmpty(list)){
				dictDetailName = list.get(0).getTbjDictDetailName();
			}
		}
		return dictDetailName;
	}

	/**
	 * 调用接口释放贷款
	 * 
	 * @throws Exception
	 */
	public void unlockLoanDetailResult(String ids) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		List<LoanDetailDto> loanList = loanDao.getLoanDetailByLoanDetailIds(paramMap);
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		doRegisterUpdateLoanDetailResult(busiNoForInteract, loanList);
		updateLoanDetailResult(loanList, busiNoForInteract);

	}

	/**
	 * 调用接口释放贷款 注册流水号
	 * 
	 * @throws Exception
	 */
	public void doRegisterUpdateLoanDetailResult(String busiNoForInteract, List<LoanDetailDto> creditDealList) {
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "updateLoanDetailResult", creditDealList,
				busiNoForInteract);
	}

	/**
	 * 调用接口释放贷款
	 * 
	 * @throws Exception
	 */
	public void updateLoanDetailResult(List<LoanDetailDto> loanList, String busiNoForInteract) throws Exception {
		// 调用释放贷款接口
		if (loanList.size() > 0) {
			List<QuotaDetailUnlockParamDto.LoanUnlockInfo> loanUnlockInfoList = new ArrayList<QuotaDetailUnlockParamDto.LoanUnlockInfo>();
			for (LoanDetailDto quotaLoanDetailDTO : loanList) {
				QuotaDetailUnlockParamDto.LoanUnlockInfo loanUnlockInfo = new QuotaDetailUnlockParamDto.LoanUnlockInfo();
				loanUnlockInfo.setContractNo(quotaLoanDetailDTO.getContractNo());
				loanUnlockInfo.setUnlockReason("人工取消");
				loanUnlockInfo.setUnlockType(CimsConstant.LOAN_OPER_TYPE_LB); // 取消额度申请/日终释放额度/人工驳回
				loanUnlockInfoList.add(loanUnlockInfo);
			}
			QuotaDetailUnlockParamDto paramDto = new QuotaDetailUnlockParamDto();
			paramDto.setQuotaType(CimsConstant.QUOTATYPE_LOAN);
			paramDto.setUnlockList(loanUnlockInfoList);
			paramDto.setDealCode(busiNoForInteract);
			// 调用释放贷款的接口
			iCInteract.quotaDetailUnlock(paramDto);
		}
	}

	/**
	 * 注册 -处理贷款导入结果- 接口
	 * 
	 * @Title doRegisterUpdateCreditDealDetailResult
	 * @Description TODO
	 * @param busiNoForInteract
	 * @param creditDealList
	 * @throws Exception
	 * @author lizhiqiang
	 * @date 2015-4-28-上午10:06:34
	 * @update
	 * @throws
	 */
	public void doLoanImportResult(List<LoanDetailDto> loanDealList, String resultType, DealDto dealDto) throws Exception {
		List<LoanDetailDto> loanDealListResult = this.doExcelLoanImport(loanDealList, resultType);
		if (CollectionsUtils.isNotEmpty(loanDealListResult))
			this.doLoanExcuteInterface(loanDealListResult, resultType, dealDto);
	}

	/**
	 * 导入贷款结果调用接口
	 * 
	 * @Title doLoanExcuteInterface
	 * @Description TODO
	 * @param loanDealList
	 * @param busiNoForInteract
	 * @param loanResultType
	 *            void
	 * @author lizhiqiang
	 * @date 2015-4-28-下午2:55:44
	 * @update
	 * @throws
	 */
	public void doLoanExcuteInterface(List<LoanDetailDto> loanDealList, String resultType, DealDto dealDto) throws Exception {
		if ("CONFIRM".equals(resultType)) {
			ConfirmParamDto approveDto = new ConfirmParamDto();
			List<ConfirmParamDto.LoanApproveInfo> approveList = new ArrayList<ConfirmParamDto.LoanApproveInfo>();
			for (LoanDetailDto loanDetailDto : loanDealList) {
				if (loanDetailDto.getLoanStatus() == null) {
					continue;
				}
				LoanApproveInfo loanApproveInfo = approveDto.new LoanApproveInfo();
				loanApproveInfo.setApproveReason("");
				loanApproveInfo.setContractNo(loanDetailDto.getContractNo());
				String loanStatus = "";
				if (loanDetailDto.getLoanStatus().equals(CimsConstant.LOAN_CONFIRM_LOSE)) {
					loanStatus = CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL;// 审批失败
				} else if (loanDetailDto.getLoanStatus().equals(CimsConstant.LOAN_CONFIRM_WIN)) {
					loanStatus = CimsIrtUrlConstant.IRT_LOAN_APPROVE_SUCCESS;// 审批通过
				}
				loanApproveInfo.setApproveType(loanStatus);
				approveList.add(loanApproveInfo);
			}
			approveDto.setBusiType(CimsConstant.QUOTATYPE_LOAN);
			approveDto.setDealCode("");
			approveDto.setApproveList(approveList);
			// 调用
			iCInteract.approveConfrim(approveDto);// 贷款确认
		} else if ("FUNDOUT".equals(resultType)) {
			LoanFundOutDto loanFundOutDto = new LoanFundOutDto();
			List<LoanFundOutInfo> loanFundOutInfoList = new ArrayList<LoanFundOutInfo>();

			for (LoanDetailDto loanDetailDto : loanDealList) {

				LoanFundOutInfo loanFundOutInfo = loanFundOutDto.new LoanFundOutInfo();
				loanFundOutInfo.setContractNo(loanDetailDto.getContractNo());
				loanFundOutInfo.setOperReason("");
				loanFundOutInfo.setPayDate(loanDetailDto.getFundDate());//放款日期
				String operType = "";
				if (loanDetailDto.getLoanStatus().equals(CimsConstant.LOAN_FUNDOUT_WIN)) {
					operType = CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_SUCCESS;

					tbjCLoanImpl.insertCreditByContractNo(loanDetailDto.getContractNo(), loanDetailDto.getFundDate());
				} else if (loanDetailDto.getLoanStatus().equals(CimsConstant.LOAN_FUNDOUT_LOSE)) {
					operType = CimsIrtUrlConstant.IRT_LOAN_FUNDOUT_FAIL;
				}
				loanFundOutInfo.setOperType(operType);
				loanFundOutInfoList.add(loanFundOutInfo);
			}
			loanFundOutDto.setDealCode("");
			loanFundOutDto.setLoanFundOutInfoList(loanFundOutInfoList);
			iCInteract.loanFundOut(loanFundOutDto);
		}

	}

	/**
	 * 交易导入处理
	 * 
	 * @param
	 * @return
	 */
	public List<LoanDetailDto> doExcelLoanImport(List<LoanDetailDto> loanDealList, String resultType) throws Exception {
		List<LoanDetailDto> loanDealListResult = new ArrayList<LoanDetailDto>();
		
		String dealCode = "";
		for (LoanDetailDto loanDetailDto : loanDealList) {
			if (SimpleStringUtils.isEmpty(loanDetailDto.getContractNo())) {
				continue;
			}
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmLoanDetailDTO loanDetailDTO = new TCMmLoanDetailDTO();
			loanDetailDTO.setContractNo(loanDetailDto.getContractNo());
			searchParams.put("dto", loanDetailDTO);
			loanDetailDTO = tCMmLoanDetailDao.searchTCMmLoanDetail(searchParams).get(0);
			
			if("".equals(dealCode)){
				dealCode = loanDetailDTO.getDealCode();
			}
			
			if ("CONFIRM".equals(resultType)) {
				if (CimsConstant.LOAN_WAY.equals(loanDetailDTO.getLoanStatus())) {
					loanDealListResult.add(loanDetailDto);// 需要调用接口

					loanDetailDTO.setLoanStatus(loanDetailDto.getLoanStatus());
					searchParams.clear();
					searchParams.put("dto", loanDetailDTO);
					tCMmLoanDetailDao.updateTCMmLoanDetail(searchParams);// 更新交易明细表
				}
			} else if ("FUNDOUT".equals(resultType)) {
				if (!CimsConstant.LOAN_FUNDOUT_WIN.equals(loanDetailDTO.getLoanStatus())
						&& !CimsConstant.LOAN_CONFIRM_LOSE.equals(loanDetailDTO.getLoanStatus())) {
					
					loanDealListResult.add(loanDetailDto);// 需要调用接口

					loanDetailDTO.setLoanStatus(loanDetailDto.getLoanStatus());
					loanDetailDTO.setFundDate(loanDetailDto.getFundDate());//放款日期
					
					loanDetailDTO.setServiceCharge(loanDetailDto.getServiceCharge());//服务费
					loanDetailDTO.setCautionMoney(loanDetailDto.getCautionMoney());//保证金
					if("01".equals(loanDetailDto.getCostState())||"00".equals(loanDetailDto.getCostState()))
					loanDetailDTO.setCostState(loanDetailDto.getCostState());
					
					searchParams.clear();
					searchParams.put("dto", loanDetailDTO);
					tCMmLoanDetailDao.updateTCMmLoanDetail(searchParams);// 更新交易明细表
					//更新募集计划项目总额
					tCMmRaisePlanService.updateTCMmRaisePlanItemSum();
				}else{
					
					loanDetailDTO.setServiceCharge(loanDetailDto.getServiceCharge());//服务费
					loanDetailDTO.setCautionMoney(loanDetailDto.getCautionMoney());//保证金
					
					if("01".equals(loanDetailDto.getCostState())||"00".equals(loanDetailDto.getCostState()))
					loanDetailDTO.setCostState(loanDetailDto.getCostState());
					
					searchParams.clear();
					searchParams.put("dto", loanDetailDTO);
					tCMmLoanDetailDao.updateTCMmLoanDetail(searchParams);// 更新交易明细表
				}
				
				
			}

		}
		//统计服务费、保证金到交易流水
		if(!"".equals(dealCode))
		tCMmLoanDetailDao.updateDealCostValues(dealCode);
		
		return loanDealListResult;
	}

	/**
	 * @throws Exception
	 *             根据贷款信息查询还款计划
	 * @Title getRefundPlanListByLoan
	 * @Description TODO
	 * @return List<TCMmRefundPlanDTO>
	 * @author lizhiqiang
	 * @date 2015-4-28-下午8:41:58
	 * @update
	 * @throws
	 */
	public List<RefundPlanDTO> getRefundPlanListByLoan(LoanDetailDto loanDetailDto) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		TCMmRefundPlanDTO refundPlan = new TCMmRefundPlanDTO();
		refundPlan.setCreditorCode(loanDetailDto.getContractNo());
		searchParams.put("dto", refundPlan);
		List<TCMmRefundPlanDTO> tlist = refundPlanService.searchTCMmRefundPlan(searchParams);
		List<RefundPlanDTO> rlist = new ArrayList<RefundPlanDTO>();
		for (TCMmRefundPlanDTO tcMmRefundPlanDTO : tlist) {
			RefundPlanDTO refundPlanDTO = new RefundPlanDTO();
			SimpleBeanUtils.copyBean2Bean(refundPlanDTO, tcMmRefundPlanDTO);
			refundPlanDTO.setPaybackAmount(tcMmRefundPlanDTO.getMustAmount().add(tcMmRefundPlanDTO.getMustAccrual()));
			rlist.add(refundPlanDTO);
		}
		return rlist;
	}

	/**
	 * 铜板街审核结果查询
	 */
	public void doAuditResultDetail() {

		String cooperorgCode = CimsConstant.TBJ_COOPERORG_CODE;

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("cooperorgCode", cooperorgCode);

		// 查询铜板街贷款明细信息
		List<LoanDetailDto> contractNoList = auditResultDao.findAuditResult(searchParams);

		if (CollectionsUtils.isNotEmpty(contractNoList)) {
			TBJResponse tBJResponse = new TBJResponse();
			AuditResultDto auditResultDto = new AuditResultDto();
			List<AuditResultDto> auditResultDtos = new ArrayList<AuditResultDto>();

			// 查询贷款审批结果
			try {
				for (LoanDetailDto loanDetailDto : contractNoList) {

					String contractNo = loanDetailDto.getContractNo();
					tBJResponse = iTBJBusinessClient.searchAudit(contractNo);
					auditResultDto = (AuditResultDto) tBJResponse.getData();
					auditResultDtos.add(auditResultDto);
				}
				// 更新贷款审核状态
				tbjCLoanImpl.updateAuditResult(auditResultDtos);
			} catch (Exception e) {
				logger.error(CimsExceptionConstant.UPDATE_AUDIT_RESULT_FIELD + e);
				throw new SysAssistException(CimsExceptionConstant.UPDATE_AUDIT_RESULT_FIELD + e);
			}
		}
	}

	/**
	 * 铜板街放款结果查询
	 */
	public void doLoanResultDetail() {

		String cooperorgCode = CimsConstant.TBJ_COOPERORG_CODE;

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("cooperorgCode", cooperorgCode);

		// 查询铜板街贷款明细信息
		List<LoanDetailDto> contractNoList = loanResultDao.findLoanResult(searchParams);
		int contractNoListLength = contractNoList.size();

		if (contractNoListLength > 0) {
			TBJResponse tBJResponse = new TBJResponse();
			LoanResultDto loanResultDto = new LoanResultDto();
			List<LoanResultDto> loanResultDtos = new ArrayList<LoanResultDto>();
			// 查询贷款放款结果
			try {
				for (LoanDetailDto loanDetailDto : contractNoList) {
					String contractNo = loanDetailDto.getContractNo();
					tBJResponse = iTBJBusinessClient.searchLoan(contractNo);
					loanResultDto = (LoanResultDto) tBJResponse.getData();
					loanResultDtos.add(loanResultDto);
				}

				// 更新贷款放款状态
				tbjCLoanImpl.updateLoanResult(loanResultDtos);
			} catch (Exception e) {
				logger.error(CimsExceptionConstant.UPDATE_LOAN_RESULT_FIELD + e);
				throw new SysAssistException(CimsExceptionConstant.UPDATE_LOAN_RESULT_FIELD + e);
			}
		}
	}

	/**
	 * 查询贷款回购包（包含二次购买的债权包）下的所有债权信息【包括月还二次购买的债权信息】 分页
	 * 
	 * @param cooperorgCode
	 * @param contractCode
	 * @param packageNum
	 * @param secondPagSuffix
	 * @param secondCode
	 * @param pageInfo
	 * @param redemptionDate
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @return
	 */
	public List<TCMmCreditDetailDTO> doLoanCreditDetailByPaging(String cooperorgCode, String contractCode, String packageNum, PageParameter pageInfo,
			String redemptionDate) {

		List<TCMmCreditDetailDTO> list = new ArrayList<TCMmCreditDetailDTO>();

		TCMmCreditDetailDTO dtoLoan = new TCMmCreditDetailDTO();
		Map<String, Object> searchCreditParams = new HashMap<String, Object>();
		QueryReqBean params = new QueryReqBean();

		// 贷款债权明细查询条件
		dtoLoan.setPackageNum(packageNum);// 债权包编号
		dtoLoan.setContractCode(contractCode);// 合约编号
		dtoLoan.setCreditSource(CimsConstant.CREDIT_SOURCE_LOA);// 债权来源"02"-来自贷款
		dtoLoan.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);// 可以选择赎回的债权

		params.setPageParameter(pageInfo);

		searchCreditParams.put("dto", dtoLoan);

		// if ("".equals(secondPagSuffix)) { // 债权来源 有二次购买和贷款
		params.setSearchParams(searchCreditParams);
		list = creditRedemptionService.getCreditDetailRedemptionList(params.getSearchParams());
		// logger.info("--------------------------债权查询分支：贷款--------------------------");

		/*
		 * }else{ String packageNumSecond = packageNum + secondPagSuffix; //
		 * 二次购买包编号 = 原债权包编号 + 二次购买包后缀 TCMmCreditDetailDTO dtoSecond = new
		 * TCMmCreditDetailDTO();
		 * 
		 * // 贷款债权月还匹配的债权明细查询条件 dtoSecond.setPackageNum(packageNumSecond);//
		 * 债权包编号 dtoSecond.setContractCode(secondCode);// 二次购买合约编号
		 * dtoSecond.setRedemptionStatus
		 * (CimsConstant.CREDIT_REDEMPTION_CK);//可以选择赎回的债权
		 * dtoSecond.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);//已转让
		 * 
		 * searchCreditParams.put("dto2", dtoSecond);
		 * params.setSearchParams(searchCreditParams); list =
		 * creditRedemptionService
		 * .getLoanRedemptionCreditDetailByPaging(params.getSearchParams());
		 * logger
		 * .info("--------------------------债权查询分支：贷款、债权--------------------------"
		 * ); }
		 */

		java.util.Date date = null;

		if (list != null && list.size() > 0 && !"".equals(redemptionDate)) {
			try {
				date = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				e.printStackTrace();			}

			list = getCreditDetailRedemptionListByInterface(list, date);
		}
		return list;
	}

	/**
	 * 查询贷款回购包（包含二次购买的债权包）下的所有债权信息【包括月还二次购买的债权信息】 不分页
	 * 
	 * @param cooperorgCode
	 * @param contractCode
	 * @param packageNum
	 * @param secondPagSuffix
	 * @param secondCode
	 * @param pageInfo
	 * @param redemptionDate
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @return
	 */
	public List<TCMmCreditDetailDTO> doLoanCreditDetail(String cooperorgCode, String contractCode, String packageNum, String redemptionDate) {

		List<TCMmCreditDetailDTO> loanList = new ArrayList<TCMmCreditDetailDTO>();
		// List<TCMmCreditDetailDTO> creditList = new
		// ArrayList<TCMmCreditDetailDTO>();
		// 贷款债权明细查询条件
		TCMmCreditDetailDTO dtoLoan = new TCMmCreditDetailDTO();
		Map<String, Object> searchLoanParams = new HashMap<String, Object>();
		dtoLoan.setPackageNum(packageNum);// 债权包编号
		dtoLoan.setContractCode(contractCode);// 合约编号
		dtoLoan.setCreditSource(CimsConstant.CREDIT_SOURCE_LOA);// 债权来源"02"-来自贷款
		dtoLoan.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);// 可以选择赎回的债权
		searchLoanParams.put("dto", dtoLoan);

		loanList = creditRedemptionService.getLoanRedemptionCreditDetail(searchLoanParams);

		/*
		 * String packageNumSecond = ""; if (!"".equals(secondPagSuffix) && null
		 * != secondPagSuffix) {
		 * 
		 * packageNumSecond = packageNum + secondPagSuffix; // 二次购买包编号 = 原债权包编号
		 * // + 二次购买包后缀 // 贷款债权月还匹配的债权明细查询条件 Map<String, Object>
		 * searchCreditParams = new HashMap<String, Object>();
		 * TCMmCreditDetailDTO dtoSecond = new TCMmCreditDetailDTO();
		 * dtoSecond.setPackageNum(packageNumSecond);// 债权包编号
		 * dtoSecond.setContractCode(secondCode);// 二次购买合约编号
		 * dtoSecond.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);//
		 * 可以选择赎回的债权
		 * dtoSecond.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);// 已转让
		 * searchCreditParams.put("dto", dtoSecond);
		 * 
		 * creditList =
		 * creditRedemptionService.getLoanRedemptionCreditDetail(searchCreditParams
		 * );
		 * 
		 * logger.info(
		 * "--------------------------回购保存：月还匹配债权数量：--------------------------"
		 * + creditList.size()); } if (creditList.size() != 0) {
		 * loanList.addAll(creditList); }
		 */

		java.util.Date date = null;

		if (loanList != null && loanList.size() > 0 && !"".equals(redemptionDate)) {
			try {
				date = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				e.printStackTrace();
			}

			loanList = getCreditDetailRedemptionListByInterface(loanList, date);
		}
		return loanList;
	}

	/**
	 * 获取回购日债权价值
	 * 
	 * @param creditDetailList
	 * @param redeemDate
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @return
	 */
	public List<TCMmCreditDetailDTO> getCreditDetailRedemptionListByInterface(List<TCMmCreditDetailDTO> creditDetailList, Date redeemDate) {

		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		iInteractAssist.registerDealIrtService(busiNoForInteract);

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(redeemDate);
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<TCMmCreditDetailDTO> resultlist = new ArrayList<TCMmCreditDetailDTO>();
		for (TCMmCreditDetailDTO tcMmCreditDetailDTO : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(tcMmCreditDetailDTO.getTransferId());
			tcMmCreditDetailDTO.setThisMakeCreditorValue(creditValueCalculateResultDto.getCreditValue());
			tcMmCreditDetailDTO.setRedeemDate(redeemDate);
			tcMmCreditDetailDTO.setRedemptionStatus(CimsConstant.DEAL_STATUS_CREATE);
			resultlist.add(tcMmCreditDetailDTO);
		}

		return resultlist;
	}

	/**
	 * 保存流水、交易明细 、更新债权主档信息RedemptionStatus（赎回债权可选状态）
	 * 
	 * @param creditDetailList
	 * @param sumCreditorValue
	 * @param detialNumber
	 * @param redemptionDate
	 * @throws Exception
	 * @author yujiazheng
	 */
	public String insertLoanCreditDetail(String redemptionDate, String cooperorgCode, String agreementCode, String contractCode, String packageName)
			throws Exception {
		List<TCMmCreditDetailDTO> creditDetailList = doLoanCreditDetail(cooperorgCode, contractCode, packageName, redemptionDate);
		String dealCode = "";
		if (creditDetailList.size() < 1) {
			logger.info("--------------------------该债权包下没有可以赎回的债权：--------------------------");
			throw new Exception("包:" + packageName + "下没有债权可以回购");
		}
		// 生成流水号
		StringBuffer dealCodesb = new StringBuffer();
		creditRedemptionService.doGetDealCode(dealCodesb);
		dealCode = dealCodesb.toString();
		logger.info("--------------------------贷款回购流水号：--------------------------" + dealCode);
		List<TCMmCreditDealDetailDTO> creditDealDetailDTOList = new ArrayList<TCMmCreditDealDetailDTO>();
		//List<RedemptionCreditDetailDto> redemptionCreditDetailDtoList = new ArrayList<RedemptionCreditDetailDto>();
		logger.info("--------------------------creditDetailList.size()：--------------------------" + creditDetailList.size());

		BigDecimal sumCreditorValue = new BigDecimal("0.0");

		for (int i = 0; i < creditDetailList.size(); i++) {
			TCMmCreditDetailDTO creditDetailDTO = creditDetailList.get(i);

			// 债权交易明细DTO组装
			TCMmCreditDealDetailDTO creditDealDetailDTO = new TCMmCreditDealDetailDTO();
			String transferId = creditDetailDTO.getTransferId();
			creditDealDetailDTO.setDealStreamCode(dealCode);// 交易流水号
			creditDealDetailDTO.setAgreementCode(creditDetailDTO.getAgreementCode());// 协议编号
			creditDealDetailDTO.setTransferId(transferId);// 债权转让编号
			creditDealDetailDTO.setCreditorId(creditDetailDTO.getCreditCode());// 债权编号
			creditDealDetailDTO.setCooperorgCode(creditDetailDTO.getCooperorgCode());// 转让合作机构编号
			creditDealDetailDTO.setCreditorStatus(creditDetailDTO.getCreditorStatus());// 债权状态
			creditDealDetailDTO.setCooperativeAgencyProType(creditDetailDTO.getCooperativeAgencyProType());// 合作机构产品类型
			creditDealDetailDTO.setMakeCreditorValue(creditDetailDTO.getThisMakeCreditorValue());// 转让债权价值[回购债权价值]--首次保存默认等于本次转让债权价值
			creditDealDetailDTO.setDeliverDate(creditDetailDTO.getDeliverDate());// 交割日期
			creditDealDetailDTO.setRedeemDate(DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd"));// 回购日期
			creditDealDetailDTO.setThisMakeCreditorValue(creditDetailDTO.getThisMakeCreditorValue());// 本次转让债权价值
			creditDealDetailDTO.setThisRepaySum(creditDetailDTO.getThisRepaySum());// 本期还款金额
			creditDealDetailDTO.setRepayPeriod(creditDetailDTO.getRepayPeriod());// 还款期数
			creditDealDetailDTO.setResidueRepayPeriod(creditDetailDTO.getResidueRepayPeriod());// 剩余还款期数
			creditDealDetailDTO.setThisCreditorValue(creditDetailDTO.getThisCreditorValue());// 当前债权价值
			creditDealDetailDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));// 创建时间
			creditDealDetailDTOList.add(creditDealDetailDTO);

			// 保存时计算回购价格总和
			sumCreditorValue = sumCreditorValue.add(creditDetailDTO.getThisMakeCreditorValue());

		}

		try {
			for (TCMmCreditDealDetailDTO tcMmCreditDealDetailDTO : creditDealDetailDTOList) {
				creditDealDetailService.insertTCMmCreditDealDetail(tcMmCreditDealDetailDTO);
			}
			logger.info("--------------------------贷款回购债权交易流水表明细保存成功--------------------------<==    Updates: :" + creditDealDetailDTOList.size());
		} catch (Exception e) {
			logger.info("--------------------------贷款回购债权交易流水表明细保存失败--------------------------");
			dealCode = "";
			throw e;
		}

		// 交易流水DTO组装
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dealCode);// 交易流水号
		cooperorgDealDTO.setCooperorgCode(cooperorgCode);// 合作机构
		cooperorgDealDTO.setDealDate(new java.util.Date());// 交易日期
		cooperorgDealDTO.setDealType(CimsConstant.DEAL_TYPE_LOAN_CREDIT_REDEEM);// 交易类型
		cooperorgDealDTO.setAgreementCode(agreementCode);// 协议编号
		cooperorgDealDTO.setContractCode(contractCode);// 合约编号
		cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);// 合作机构交易状态
		cooperorgDealDTO.setDetialNumber(creditDetailList.size());// 明细数目
		cooperorgDealDTO.setSumCreditorValue(sumCreditorValue);// 汇总债权价值
		cooperorgDealDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));// 创建时间
		cooperorgDealDTO.setBillDate(creditDetailList.get(0).getBillDate());// 账单日
		cooperorgDealDTO.setCreditPackageName(packageName);// 债权包名
		cooperorgDealDTO.setRedemptionDate(DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd"));// 回购日期
		UserInfo userInfo = sessionAPI.getCurrentUserInfo();
		if (userInfo != null) {
			cooperorgDealDTO.setCreateBy(userInfo.getUserId().toString());// 创建人
			cooperorgDealDTO.setModifyBy(userInfo.getUserId().toString());// 修改人
		}
		cooperorgDealDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));// 修改时间

		try {
			cooperorgDealService.insertTCMmCooperorgDeal(cooperorgDealDTO);
			logger.info("--------------------------贷款回购合作机构交易流水表保存成功--------------------------");
		} catch (Exception e) {
			logger.info("--------------------------贷款回购合作机构交易流水表保存失败--------------------------");
			dealCode = "";
			throw e;
		}

		// 债权主档信息状态更新
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dealCode", dealCode);
		paramMap.put("redemptionStatus", CimsConstant.CREDIT_REDEMPTION_UNCK);// 回购状态
																				// --
																				// 交易占用
																				// 02-已经选择
		try {
			dealDao.updateTcmmCreditDetailByDealCode(paramMap);
			logger.info("--------------------------债权主档信息状态更新成功--------------------------");
		} catch (Exception e) {
			logger.info("--------------------------债权主档信息状态更新失败--------------------------");
			dealCode = "";
			throw e;
		}

		return dealCode;
	}

	/**
	 * 验证excel数据是否准确
	 * 
	 * @param creditDetailList
	 * @param dto
	 * @throws Exception
	 * @author yujiazheng
	 */
	public void doImportCheck(List<CreditDetailDto> creditDetailList, LoanRedemptionDto dto) throws Exception {
		if (creditDetailList.size() <= 0) {
			throw new Exception("回购内容不能为空！");
		}
		for (int i = 0; i < creditDetailList.size(); i++) {
			CreditDetailDto creditDetailDto = creditDetailList.get(i);
			if (!SimpleStringUtils.hasText(creditDetailDto.getBorrowerName())) {
				throw new Exception("借款人姓名不能为空！");
			}
			if (creditDetailDto.getRedeemDate() == null) {
				throw new Exception("回购日期不能为空！");
			}
			if (creditDetailDto.getTransferId() == null) {
				throw new Exception("债权转让编号不能为空！");
			}
			if (creditDetailDto.getDealMakeCreditorValue() == null) {
				logger.info("-----------------------1转让编号:" + creditDetailDto.getTransferId() + "回购价格:" + creditDetailDto.getDealMakeCreditorValue()
						+ "-------------");
				throw new Exception("回购价格不能为空！");
			}
			if (creditDetailDto.getDealMakeCreditorValue().compareTo(new BigDecimal("0.0")) < 0) {
				logger.info("-----------------------2转让编号:" + creditDetailDto.getTransferId() + "回购价格:" + creditDetailDto.getDealMakeCreditorValue()
						+ "-------------");
				throw new Exception("回购价格不能小于0元！");
			}
		}
	}

	/**
	 * 导入更新callback方法具体实现方法
	 * 
	 * @param dto
	 * @throws Exception
	 * @author yujiazheng
	 */
	public void updateTCMmCreditDealDetail(LoanRedemptionDto dto) throws Exception {
		List<CreditDetailDto> creditDetailList = dto.getCreditDetailList();

		String dealCode = dto.getDealCode();// 获取流水号

		if (!SimpleStringUtils.hasText(dealCode)) {
			throw new Exception("流水号获取失败！");
		}

		Map<String, Object> updateParams = null;
		BigDecimal sumCreditorValue = new BigDecimal("0.0");
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			updateParams = new HashMap<String, Object>();
			updateParams.put("dto", creditDetailDto);
			updateParams.put("dealStreamCode", dealCode);
			// 更新回购价格 条件:流水号+转让编号
			dealDao.updateLoanDealDetail(updateParams);

			sumCreditorValue = sumCreditorValue.add(creditDetailDto.getDealMakeCreditorValue());// 回购价格合计
		}

		// 更新合作机构交易流水表的回购价格总和
		Map<String, Object> searchParams = new HashMap<String, Object>();
		TCMmCooperorgDealDTO tcMmCooperorgDealDTO = new TCMmCooperorgDealDTO();

		tcMmCooperorgDealDTO.setDealCode(dealCode);// 交易流水号
		tcMmCooperorgDealDTO.setCooperorgCode(dto.getCooperorgCode());// 合作机构
		tcMmCooperorgDealDTO.setContractCode(dto.getContractCode());// 协议编号
		tcMmCooperorgDealDTO.setAgreementCode(dto.getAgreementCode());// 合约编号

		searchParams.put("dto", tcMmCooperorgDealDTO);
		List<TCMmCooperorgDealDTO> tCMmCooperorgDealDTOList = cooperorgDealService.searchTCMmCooperorgDeal(searchParams);
		UserInfo userInfo = sessionAPI.getCurrentUserInfo();
		if (tCMmCooperorgDealDTOList.size() >= 1) {
			TCMmCooperorgDealDTO updateCooperorgDealDTO = tCMmCooperorgDealDTOList.get(0);
			updateCooperorgDealDTO.setSumCreditorValue(sumCreditorValue);
			if (userInfo != null) {
				updateCooperorgDealDTO.setModifyBy(userInfo.getUserId().toString());// 修改人
			}
			updateCooperorgDealDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));// 修改时间
			cooperorgDealService.updateTCMmCooperorgDeal(updateCooperorgDealDTO);
		} else {
			throw new Exception("信息有误！");
		}

	}

	/**
	 * 根据流水号获取回购价格合计、回购债权价值合计
	 * 
	 * @param dealCode
	 * @return
	 * @author yujiazheng
	 */
	public CreditRightDto getDealDetailByCreditSumTotal(String dealCode) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dealCode", dealCode);
		return dealDao.getSumValueByLoanListByTotal(searchParams);
	}


	/**
	 * 删除功能具体实现
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 * @author yujiazheng
	 */
	public String doDeleteDeal(String ids) throws Exception {
		StringBuffer resultstr = new StringBuffer("交易流水号（");
		String[] id = ids.split(",");
		int count = 0;
		for (int i = 0; i < id.length; i++) {
			TCMmCooperorgDealDTO cooperorgDealDTO = cooperorgDealService.queryTCMmCooperorgDealByPrimaryKey(id[i]);

			if (CimsConstant.DEAL_STATUS_CREATE.equals(cooperorgDealDTO.getCooperativeAgencyDealStatus())||CimsConstant.DEAL_STATUS_WAY.equals(cooperorgDealDTO.getCooperativeAgencyDealStatus())
					|| SimpleStringUtils.isEmpty(cooperorgDealDTO.getCooperativeAgencyDealStatus())) {

				String dealCode = cooperorgDealDTO.getDealCode();// 交易流水号

				// -----------------------修改合作机构交易流水表 状态 validate_state='0'
				// -----------------------
				try {
					cooperorgDealService.deleteTCMmCooperorgDealByPrimaryKey(new BaseDTO(), id[i]);
					logger.info("--------------修改合作机构交易流水表状态成功，交易流水号：--------------------" + dealCode);
				} catch (Exception e) {
					logger.error("--------------修改合作机构交易流水表状态失败，交易流水号：--------------------" + dealCode);
					throw (e);
				}
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("dealCode", dealCode);
				paramMap.put("redemptionStatus", CimsConstant.CREDIT_REDEMPTION_CK);// 01-可选
				// -----------------------更新债权明细状态 去掉占用标志
				// 根据交易流水号-----------------------
				try {
					dealDao.updateTcmmCreditDetailByDealCode(paramMap);
					logger.info("--------------更新债权明细状态成功，交易流水号：--------------------" + dealCode);
				} catch (Exception e) {
					logger.error("--------------更新债权明细状态失败，交易流水号：--------------------" + dealCode);
					throw (e);
				}
				// -----------------------删除债权交易明细
				// 根据交易流水号----------------------------------
				try {
					dealDao.deleteTcmmCreditDealDetaByDealCode(paramMap);
					logger.info("--------------删除债权交易明细成功，交易流水号：--------------------" + dealCode);
				} catch (Exception e) {
					logger.error("--------------删除债权交易明细失败，交易流水号：--------------------" + dealCode);
					throw (e);
				}
			} else {
				count++;
				resultstr.append(cooperorgDealDTO.getDealCode() + ",");
			}
		}

		if ("交易流水号（".equals(resultstr.toString())) {
			resultstr = new StringBuffer("");
			resultstr.append("删除成功");
		} else {
			if (count > 0)
				resultstr.append("已经进入交易状态，不能删除，其余删除成功");
			else
				resultstr.append("已经进入交易状态，不能删除");
		}
		return resultstr.toString();
	}
	
	
	/**
	 * 删除功能具体实现
	 * 
	 * @param creditCode    合同号
	 *  @param creditorStatus 债权状态
	 * @return
	 * @throws Exception
	 * @author zhoupeng
	 */
	public String doReleaseDeal(String creditCode,String creditorStatus,String dealCode) throws Exception {
		if (CimsConstant.CREDIT_STATUS_RED.equals(creditorStatus)) {
			throw new RuntimeException("债权为赎回状态，不能删除");
		}
		creditRedemptionService.removeDetailByCredit(new BaseDTO(), creditCode, dealCode);
		return "合同号:"+creditCode+ "删除成功";
	}

	/**
	 * 根据交易流水好获取贷款信息
	 * @author zhangmi
	 * @date  2016年8月24日
	 * @param dealCode
	 * @return
	 */
	public List<LoanDetailDto> getLoanDetailByDealCode(String dealCode) {
		DealDto dto = new DealDto();
		dto.setDealCode(dealCode);
		return loanDao.getDealDetailByLoanList(SearchParamUtil.getSearchParam(dto));
	}
	
	/**
	 * 更新贷款服务费用
	 * @author zhangmi
	 * @date  2016年9月2日
	 * @param list
	 */
	public void updateLoanDetailFeesByList(List<LoanDetailDto> list) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for (LoanDetailDto loanDetailDto : list) {
			paramMap.clear();
			paramMap.put("dto", loanDetailDto);
			loanDao.updateLoanDetailsFee(paramMap);
		}
	}
	
	/**
	 * 修改费用总和
	 * @author zhangmi
	 * @date  2016年9月7日
	 * @param dealCode
	 * @throws Exception
	 */
	public void updateLoanFeesTotal(String dealCode) throws Exception{
		tCMmLoanDetailDao.updateDealCostValues(dealCode);
	}
	
}